/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain an copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.slice.picker;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.multimodalinput.event.KeyEvent;

import com.google.gson.reflect.TypeToken;
import com.xuexiang.xui_lib.component.button.SuperButton;
import com.xuexiang.xui_lib.component.picker.ProvinceInfo;
import com.xuexiang.xui_lib.component.picker.widget.BasePickerView;
import com.xuexiang.xui_lib.component.picker.widget.OptionsPickerView;
import com.xuexiang.xui_lib.component.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui_lib.component.picker.widget.listener.OnDismissListener;
import com.xuexiang.xui_lib.util.StatusBarUtils;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.util.DialogPickerValueChange;
import com.xuexiang.xuidemo.util.JsonUtil;
import com.xuexiang.xuidemo.util.ToastUtil;
import com.xuexiang.xuidemo.view.CityPickerCenterDialog;
import com.xuexiang.xuidemo.view.CityPickerDialog;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 描述 城市三级选择页
 *
 * @author name
 * @since 2021-04-19
 */
public class AddressPickerAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Image imageBack;
    private Text textTitle;
    private Text textTitleBottom;
    private List<ProvinceInfo> options1Items = new ArrayList<>();
    private List<List<String>> options2Items = new ArrayList<>();
    private List<List<List<String>>> options3Items = new ArrayList<>();
    private Component mComponent;
    private boolean mHasLoaded;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        StatusBarUtils.translucent();
        StatusBarUtils.fullScreen();
        super.setUIContent(ResourceTable.Layout_ability_city_picker);
        initView();
        loadData(getProvinceInfos());
    }

    private void initView() {
        imageBack = (Image) findComponentById(ResourceTable.Id_image_back);
        textTitle = (Text) findComponentById(ResourceTable.Id_text_title);
        textTitle.setText("OptionsPicker");
        textTitleBottom = (Text) findComponentById(ResourceTable.Id_text_title_bottom);
        mComponent = (Component) findComponentById(ResourceTable.Id_component);
        textTitleBottom.setText("条件选择器--省市区三级联动");
        imageBack.setClickedListener(this);
        SuperButton showCityPicker = (SuperButton) findComponentById(ResourceTable.Id_city_picker);
        showCityPicker.setClickedListener(this);
        SuperButton dialogCityPicker = (SuperButton) findComponentById(ResourceTable.Id_dialog_city_picker);
        dialogCityPicker.setClickedListener(this);
    }

    private void loadData(List<ProvinceInfo> provinceInfos) {//加载数据
        /**
         * 添加省份数据
         */
        options1Items = provinceInfos;

        //遍历省份（第一级）
        for (ProvinceInfo provinceInfo : provinceInfos) {
            //该省的城市列表（第二级）
            List<String> cityList = new ArrayList<>();
            //该省的所有地区列表（第三级）
            List<List<String>> areaList = new ArrayList<>();

            for (ProvinceInfo.City city : provinceInfo.getCityList()) {
                //添加城市
                String cityName = city.getName();
                cityList.add(cityName);
                //该城市的所有地区列表
                List<String> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (city.getArea() == null || city.getArea().size() == 0) {
                    cityAreaList.add("");
                } else {
                    cityAreaList.addAll(city.getArea());
                }
                //添加该省所有地区数据
                areaList.add(cityAreaList);
            }

            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(areaList);
        }

        mHasLoaded = true;
    }

    private void showDialog2() {
        CityPickerCenterDialog cityPickerCenterDialog = new CityPickerCenterDialog(getAbility());
        cityPickerCenterDialog.setDialogPickerValueChange(new DialogPickerValueChange() {
            @Override
            public void valueChange(String message) {
                new ToastDialog(getContext())
                    .setText(message)
                    // Toast显示在界面中间
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
            }
        });
        cityPickerCenterDialog.show();
    }

    private void showDialog() {
        CityPickerDialog cityPickerDialogFragment = new CityPickerDialog(getAbility());
        cityPickerDialogFragment.setDialogPickerValueChange(new DialogPickerValueChange() {
            @Override
            public void valueChange(String message) {
                new ToastDialog(getContext())
                    .setText(message)
                    // Toast显示在界面中间
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
            }
        });
        cityPickerDialogFragment.show();
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_image_back:
                onBackPressed();
                break;
            case ResourceTable.Id_city_picker:
                //showDialog();
                showPickerView(true);
                break;
            case ResourceTable.Id_dialog_city_picker:
                // showDialog2();
                showPickerView(false);
                break;
            default:
                break;
        }
    }

    private void showPickerView(boolean isDialog) {
        mComponent.setVisibility(Component.VISIBLE);
        // 弹出选择器
        if (!mHasLoaded) {
            ToastUtil.showToast(this, "数据加载中...");
            return;
        }

        int[] defaultSelectOptions = getDefaultCity();
        Color color = Color.BLACK;
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), (v, options1, options2, options3) -> {
            //返回的分别是三个级别的选中位置
            String tx = options1Items.get(options1).getPickerViewText() + "-" +
                options2Items.get(options1).get(options2) + "-" +
                options3Items.get(options1).get(options2).get(options3);

            ToastUtil.showToast(this, tx);
            return false;
        })
            .setTitleText("城市选择")
            .setDividerColor(color.getValue())
            //切换选项时，还原到第一项
            .isRestoreItem(true)
            //设置选中项文字颜色
            .setTextColorCenter(color.getValue())
            .setContentTextSize(20)
            .setSelectOptions(defaultSelectOptions[0], defaultSelectOptions[1], defaultSelectOptions[2])
            .isDialog(isDialog)
            .setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(BasePickerView pickerView) {
                    mComponent.setVisibility(Component.HIDE);
                }
            })
            .build();
        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    /**
     * 获取迭代器对象信息数组
     *
     * @return 省市区数据
     */
    public List<ProvinceInfo> getProvinceInfos() {
        return JsonUtil.fromJson(loadJson(), new TypeToken<List<ProvinceInfo>>() {
        }.getType());
    }

    /**
     * 获取默认的城市
     *
     * @return 获取默认城市的索引
     */
    private int[] getDefaultCity() {
        int[] res = new int[3];
        ProvinceInfo provinceInfo;
        List<ProvinceInfo.City> cities;
        ProvinceInfo.City city;
        List<String> ares;
        for (int i = 0; i < options1Items.size(); i++) {
            provinceInfo = options1Items.get(i);
            if ("江苏省".equals(provinceInfo.getName())) {
                res[0] = i;
                cities = provinceInfo.getCityList();
                for (int j = 0; j < cities.size(); j++) {
                    city = cities.get(j);
                    if ("南京市".equals(city.getName())) {
                        res[1] = j;
                        ares = city.getArea();
                        for (int k = 0; k < ares.size(); k++) {
                            if ("雨花台区".equals(ares.get(k))) {
                                res[2] = k;
                                break;
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
        return res;
    }

    /**
     * 获取json字符串
     *
     * @return Json字符
     */
    private String loadJson() {
        String json = null;
        ResourceManager manager = getAbilityPackageContext().getResourceManager();
        RawFileEntry entry = manager.getRawFileEntry("resources/rawfile/province.json");
        try {
            Resource res = entry.openRawFile();
            int size = res.available();
            byte[] buffer = new byte[size];
            res.read(buffer);
            res.close();
            json = new String(buffer, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param keyEvent
     * @return boolean
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent keyEvent) {
        mComponent.setVisibility(Component.HIDE);
        return super.onKeyUp(keyCode, keyEvent);
    }
}
